package org.developer.study.springboot.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonUtil {
	
	private static ObjectMapper mapper = new ObjectMapper();

	/**
	 * 将对象转成json
	 */
	public static <T> String toJson (T obj) {
		String json = null;
		try {
			json = mapper.writeValueAsString(obj);
		}catch(Exception e) {
			System.out.println(e);
			throw new RuntimeException(e);
		}
		return json;
	}
	/**
	 * 将json转化成非泛型的对象
	 * jackson将json转成非泛型和转成泛型对象是不一样的处理，具体看下面
	 * transformJson2Generic方法 
	 */
	public static <T> T toObject(String json ,Class<T> clazz) {
		T obj = null;
		try {
			obj = mapper.readValue(json,clazz);
		}catch(Exception e) {
			System.out.println(e);
			throw new RuntimeException(e);
		}
		return obj;
	}
	
	/**
	 * 将json转化成泛型的对象，eg:List<User>
	 * [{\"username\":\"shangguanls\",\"age\":\"23\"},{\"username\":\"shangguanls\",\"age\":\"23\"}]
	 * 涉及泛型使用TypeReference
	 */
//	public static <T> List<User> transformJson2Generic(String json,TypeReference<T> valueTypeRef) {
//		List<User> users = null;
//		try {
//			users = mapper.readValue(json, valueTypeRef);
//			System.out.println(users);
//		}catch(Exception e) {
//			System.out.println(e);
//			throw new RuntimeException(e);
//		}
//		return users;
//	}
}
	